package com.air.common.service.imp;

import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.air.common.dao.BaseDao;
import com.air.common.exception.OutofPageBoundException;
import com.air.common.service.IBaseService;
import com.air.common.util.QueryCondition;
import com.air.common.util.QueryCondition4Update;
import com.air.common.vo.PageResultListVO;


public class BaseServiceImp implements IBaseService{
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
	protected BaseDao baseDao;
	
	@Override
	public int deleteByCondition(QueryCondition condition) {
		return baseDao.deleteByCondition(condition);
	}
	
	public int deleteById(int id){
		return baseDao.deleteById(id);
	}
	
	@Override
	public <T> T findById(int id) {
		return baseDao.selectById(id);
	}

	@Override
	public <T> T insert(T object) throws Exception{
		baseDao.insert(object);
		return object;
	}

	@Override
	public <T> List<T> queryByCondition(QueryCondition condition) {
		return baseDao.queryByCondition(condition);
	}

	@Override
	public PageResultListVO queryByCondition(QueryCondition condition,
			int curPageNum, int pageLimit) throws OutofPageBoundException {
		
		
		int offset = curPageNum*pageLimit;
		RowBounds rowBounds = new RowBounds(offset,pageLimit);
		
		int totalRecorderCount = baseDao.countByCondition(condition);
		if (offset > totalRecorderCount){
			throw new OutofPageBoundException("Request PAGE_NUM="+curPageNum+" And PAGE_LIMIT="+pageLimit+" is out of result bound,TOTAL_RECORD_COUNT="+totalRecorderCount);
		}
		
		List<?> pageResult=baseDao.queryByCondition(condition, rowBounds);
		
		PageResultListVO resultListVO = new PageResultListVO();
		resultListVO.setPageLimit(pageLimit);
		resultListVO.setPageNum(curPageNum);
		resultListVO.setResult(pageResult);
		resultListVO.setTotalRecorderCount(totalRecorderCount);
		
		return resultListVO;
		
	}

	@Override
	public int updateByCondition(QueryCondition4Update condition) {
		return baseDao.updateByCondition(condition);
	}

	@Override
	public <T> int updateById(T object) {
		return baseDao.updateById(object);
	}
	
	@Override
	public int countByCondition(QueryCondition condition){
		return baseDao.countByCondition(condition);
	}
	
}
